﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using AutoHistory.Core;
using System.IO;

namespace AutoHistory2010ForExcel
{
    public partial class ThisAddIn
    {
        public Microsoft.Office.Tools.CustomTaskPane taskPane;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            this.Application.WorkbookBeforeSave += new Excel.AppEvents_WorkbookBeforeSaveEventHandler(Application_WorkbookBeforeSave);
            this.Application.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);
            this.Application.WindowActivate += new Excel.AppEvents_WindowActivateEventHandler(Application_WindowActivate);

            if (Settings.Instance.Language > 1000)
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Settings.Instance.Language);
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Settings.Instance.Language);
            }

            CreateTaskPane();
        }

        void Application_WindowActivate(Excel.Workbook Wb, Excel.Window Wn)
        {
            SetCurrentDocumentTaskPane(Wb);
        }

        void Application_WorkbookOpen(Excel.Workbook Wb)
        {
            string currentFile = GetCurrentFile(Wb);

            CreateTaskPane();

            HistoryTaskPane form = GetTaskPaneControl();
            form.SetSourceFile(currentFile);
            form.UpdateHistory();
        }

        void Application_WorkbookBeforeSave(Excel.Workbook Wb, bool SaveAsUI, ref bool Cancel)
        {
            if (Wb.Saved)
                return;

            string currentFile = GetCurrentFile(Wb);
            if (String.IsNullOrEmpty(currentFile))
                return;

            try
            {
                HistoryManager.AddFile(currentFile);

                HistoryTaskPane form = GetTaskPaneControl();
                form.SetSourceFile(currentFile);
                form.UpdateHistory();
            }
            catch (Exception ex)
            {
                HistoryTaskPane tpform = GetTaskPaneControl();
                if (tpform != null)
                    tpform.SetStatus(ex.Message);
            }
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        private void CreateTaskPane()
        {
            var taskPane = this.CustomTaskPanes.Add(new HistoryTaskPane(this.Application), "AutoHistory");
            this.SetTaskPane(taskPane);
        }

        private void SetCurrentDocumentTaskPane(Microsoft.Office.Interop.Excel.Workbook wb)
        {
            string currentFile = GetCurrentFile(wb);

            this.SetTaskPane(GetTaskPane());

            HistoryTaskPane form = GetTaskPaneControl();
            if (form == null)
                return;
            form.SetSourceFile(currentFile);
            form.UpdateHistory();
        }

        private string GetCurrentFile(Microsoft.Office.Interop.Excel.Workbook wb)
        {
            string currentPath = wb.Path;
            string filename = wb.Name;

            if (String.IsNullOrEmpty(currentPath) || String.IsNullOrEmpty(filename))
                return string.Empty;

            return Path.Combine(currentPath, filename);
        }

        private Microsoft.Office.Tools.CustomTaskPane GetTaskPane()
        {
            foreach (var ctp in this.CustomTaskPanes)
            {
                if (ctp.Control is HistoryTaskPane)
                {
                    try
                    {
                        if (ctp.Window != null)
                        {
                            var window = (Microsoft.Office.Interop.Excel.Window)ctp.Window;
                            if (window.ActiveSheet != null)
                                return ctp;
                        }
                    }
                    catch (System.Runtime.InteropServices.InvalidOleVariantTypeException) { }
                    catch { }
                }
            }
            return null;
        }

        private HistoryTaskPane GetTaskPaneControl()
        {
            var tp = GetTaskPane();
            if (tp == null)
                return null;

            return (tp.Control as HistoryTaskPane);
        }

        private void SetTaskPane(Microsoft.Office.Tools.CustomTaskPane taskPane)
        {
            if (taskPane == null)
                return;
            this.taskPane = taskPane;
            this.taskPane.Visible = Settings.Instance.IsPaneVisible;
            this.taskPane.VisibleChanged += new EventHandler(taskPane_VisibleChanged);
        }

        void taskPane_VisibleChanged(object sender, EventArgs e)
        {
            Settings.Instance.IsPaneVisible = this.taskPane.Visible;
            Settings.Instance.Save();
        }
        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
